package com.gukewen.aihaiguitang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gukewen.aihaiguitang.entity.Conversation;
import com.gukewen.aihaiguitang.entity.ConversationMessage;
import com.gukewen.aihaiguitang.entity.dto.PageDTO;
import com.gukewen.aihaiguitang.entity.vo.StartVO;
import com.gukewen.aihaiguitang.mapper.ConversationMapper;
import com.gukewen.aihaiguitang.mapper.ConversationMessageMapper;
import com.gukewen.aihaiguitang.service.ChatService;
import com.gukewen.aihaiguitang.util.AiUtil;
import com.gukewen.aihaiguitang.util.Result;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessage;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessageRole;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

@Service
public class ChatServiceImpl implements ChatService {

    @Resource
    private ConversationMapper conversationMapper;

    @Resource
    private ConversationMessageMapper conversationMessageMapper;

    @Value("${ai.system-prompt}")
    private String systemPrompt;

    @Value("${ai.openingLine}")
    private String openingLine;

    @Resource
    private AiUtil aiUtil;


    @Override
    public StartVO start() {
        // 1.创建会话
        Conversation conversation = new Conversation();
        conversation.setName(" ");
        conversationMapper.insert(conversation);

        // 2.修改会话名称
        conversation.setName("黑暗诡事馆-" + conversation.getId());
        conversationMapper.updateById(conversation);

        // 3.返回会话信息
        StartVO startVO = new StartVO();
        startVO.setRoomId(conversation.getId());
        startVO.setOpeningLine(openingLine);
        return startVO;
    }

    @Override
    public IPage<Conversation> getRoomPage(PageDTO pageDTO) {
        IPage<Conversation> page = new Page<>(pageDTO.getPage(), pageDTO.getSize());
        IPage<Conversation> pageResult = conversationMapper.selectPage(page, null);
        return pageResult;
    }


    @Override
    public Result send(Long roomId, String message) {
        // 1.初始化系统消息和用户消息
        final List<ChatMessage> messages = new ArrayList<>();
        final ChatMessage systemMessage = ChatMessage.builder().role(ChatMessageRole.SYSTEM).content(systemPrompt).build();
        final ChatMessage userMessage = ChatMessage.builder().role(ChatMessageRole.USER).content(message).build();

        // 2. 判断是否是首次发送消息（查询该房间号在数据库中是否存在并且历史对话表是否为空）
        if (conversationMapper.selectById(roomId) != null && conversationMessageMapper.selectById(roomId) == null && message.contains("开始")) {
            // 3. 如果是首次发送消息，则将系统预设到消息列表中
            messages.add(systemMessage);
            ConversationMessage assistantMessageObject1 = new ConversationMessage();
            assistantMessageObject1.setConversationId(roomId);
            assistantMessageObject1.setContent(openingLine);
            assistantMessageObject1.setRole("assistant");
            assistantMessageObject1.setCreateTime(LocalDateTime.now());
            conversationMessageMapper.insert(assistantMessageObject1);
        } else {
            // 4. 如果不是首次发送消息，则只需要读取数据库中的历史消息列表
            QueryWrapper<ConversationMessage> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("conversation_id", roomId);
            queryWrapper.orderByAsc("id");
            List<ConversationMessage> conversationMessages = conversationMessageMapper.selectList(queryWrapper);
            for (ConversationMessage conversationMessage : conversationMessages) {
                messages.add(ChatMessage.builder()
                        .role(conversationMessage.getRole().equals("user")
                                ? ChatMessageRole.USER
                                : ChatMessageRole.ASSISTANT)
                        .content(conversationMessage.getContent())
                        .build());
            }
        }
        // 将用户消息添加到消息列表中，并且持久化用户信息到数据库
        messages.add(userMessage);
        ConversationMessage ueserMessageObject = new ConversationMessage();
        ueserMessageObject.setConversationId(roomId);
        ueserMessageObject.setContent(message);
        ueserMessageObject.setRole("user");
        ueserMessageObject.setCreateTime(LocalDateTime.now());
        conversationMessageMapper.insert(ueserMessageObject);


        // 5. 调用DeepsSeek 接口，获取AI的回答,并持久化到数据库中
        String aiResponse = aiUtil.dochat(messages);
        //final ChatMessage aiMessage = ChatMessage.builder().role(ChatMessageRole.ASSISTANT).content(aiResponse).build();
        ConversationMessage assistantMessageObject2 = new ConversationMessage();
        assistantMessageObject2.setConversationId(roomId);
        assistantMessageObject2.setContent(aiResponse);
        assistantMessageObject2.setRole("assistant");
        assistantMessageObject2.setCreateTime(LocalDateTime.now());
        conversationMessageMapper.insert(assistantMessageObject2);


        // 6. 构造列表并返回最新的消息列表
        QueryWrapper<ConversationMessage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("conversation_id", roomId);
        queryWrapper.orderByAsc("create_time");
        List<ConversationMessage> conversationMessages = conversationMessageMapper.selectList(queryWrapper);

        return Result.success(conversationMessages);
    }


    @Override
    public Result getDetail(Long roomId) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("conversation_id", roomId);
        queryWrapper.orderByAsc("create_time");
        List<ConversationMessage> conversationMessages = conversationMessageMapper.selectList(queryWrapper);
        return Result.success(conversationMessages);
    }
}
